package com.hqbzl.c1;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class CallBack {
    public static void main(String[] args) {
        Switch<String> object = new Switch<>() {
            @Override
            public void call(String s) {
                System.out.println("call = " + s.length());
            }
        };
        new Thread(() -> {
            log.debug("wait result");
            final String str = object.get(1000);
            if (str == null) {
                log.debug("timeout");
            } else {
                log.debug("{}", str.length());
            }
        }, "t1").start();
        new Thread(() -> {
            try {
                final String downStr = HttpUtils.down();
                object.succ(downStr);
            } catch (Exception exception) {
                object.setException(exception);
            }
        }, "t2").start();
    }

}

abstract class Switch<T> {


    private T data;
    private Exception exception;

    public abstract void call(T t);

    public void setException(Exception exception) {
        this.exception = exception;
    }

    public Exception getException() {
        return this.exception;
    }

    public T get(long t) {
        synchronized (this) {
            while (data == null) {
                try {
                    this.wait(t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        call(this.data);
        return this.data;
    }

    public T get() {
        return get(0);
    }

    public void succ(T t) {
        synchronized (this) {
            this.data = t;
            this.notify();
        }
    }
}
